package com.frog.queue.starter.sns.config;

import org.springframework.util.Assert;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.SnsClientBuilder;
import software.amazon.awssdk.utils.StringUtils;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wuqiong 2022/4/12
 * @description
 */
public class SnsEndpointFactory {

    private static final Map<String, SnsClient> endpointMap = new ConcurrentHashMap<>();
    private static final String defaultStr = "defaults";

    /**
     * get sns client endpoint
     *
     * @param clientName
     * @return SnsClient
     * @author wuqiong 2022/4/12 14:27
     */
    public static SnsClient getSnsClient(String clientName) {
        if (StringUtils.isBlank(clientName)) clientName = defaultStr;
        return endpointMap.get(clientName);
    }

    /**
     * create batch sns client
     *
     * @param snsConfig
     * @author wuqiong 2022/4/12 14:13
     */
    public static void createBatchByConfig(SnsConfig snsConfig) {
        Assert.isTrue(!snsConfig.getInstances().isEmpty(), "Sns config 为空,请检查");
        if (!snsConfig.getInstances().containsKey(defaultStr)) {
            Optional<String> first = snsConfig.getInstances().keySet().stream().findFirst();
            SnsClient snsClient = createSnsClient(first.get(), snsConfig.getInstances().get(first.get()));
            endpointMap.put(first.get(), snsClient);
            endpointMap.put(defaultStr, snsClient);
        }
        snsConfig.getInstances().forEach((k, v) -> endpointMap.put(k, createSnsClient(k, v)));
    }

    /**
     * create sns client by config endpointInstance
     *
     * @return SnsClient
     * @author wuqiong 2022/4/12 13:22
     */
    public static synchronized SnsClient createSnsClient(String clientName, SnsConfig.EndpointInstance endpointInstance) {
        Assert.isTrue(endpointInstance != null, "endpointInstance is null , please check ");
        if (endpointMap.containsKey(clientName)) return endpointMap.get(clientName);
        SnsClientBuilder builder = SnsClient.builder();
        builder.region(Region.of(endpointInstance.getRegion()));
        if (StringUtils.isNotBlank(endpointInstance.getAccessKeyId()) && StringUtils.isNotBlank(endpointInstance.getSecretAccessKey())) {
            builder.credentialsProvider(StaticCredentialsProvider.create(
                    AwsBasicCredentials.create(endpointInstance.getAccessKeyId(), endpointInstance.getSecretAccessKey())));
        }
        return builder.build();
    }
}
